package org.dean.webapps.projectname.presentation.interceptor;

import org.dean.webapps.projectname.presentation.utils.RequestUtils;
import org.dean.webapps.projectname.utils.URLUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.*;
import java.util.regex.Pattern;

import static org.dean.webapps.projectname.presentation.utils.RequestUtils.getUriFromRequest;

/**
 * Created by IntelliJ IDEA.
 * User: dean
 * Date: 8/22/11
 * Time: 11:28 AM
 * To change this template use File | Settings | File Templates.
 */
public class EnvironmentInterceptor extends HandlerInterceptorAdapter {

    private Log log = LogFactory.getLog(this.getClass());

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        // Saves Context path of server.
        if (StringUtils.isEmpty(URLUtils.getServerContextPath())) {
            URLUtils.setServerContextPath(request);
        }
//        System.out.println(getUriFromRequest(request));

        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
//        modelAndView.getModel().put("context-path", request.getContextPath());
        super.postHandle(request, response, handler, modelAndView);

        Enumeration<String> enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String key =  enumeration.nextElement();
            request.setAttribute(key,request.getParameter(key));
        }

//        try {
//            List<Cookie> cookies = (List<Cookie>) request.getSession().getAttribute(ATTRIBUTE_COOKIES);
//            for (int i = 0; cookies != null && i < cookies.size(); i++) {
//                response.addCookie(cookies.get(i));
//            }
//        } catch (NullPointerException e) {
//
//        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {

        String currentUrl = getUriFromRequest(request);
        Pattern ajaxUrlPattern = Pattern.compile(
                String.format("%s", ".*/ajax/.*"));
//        System.out.println("regex: " + String.format("^%s%s$", URLUtils.getServerContextPath(), ".*/ajax/.*"));
        System.out.println("now: " + getUriFromRequest(request));
        if (!ajaxUrlPattern.matcher(currentUrl).find()) {
            System.out.println("record: " + getUriFromRequest(request));
            RequestUtils.setPreviousUrl(request, "");
            RequestUtils.setPreviousUrl(request, currentUrl);
        }

        super.afterCompletion(request, response, handler, ex);
    }

}